<?php

/**
 * user actions.
 *
 * @package    myarticles
 * @subpackage user
 * @author     Apul Gupta<apulmca2k4@gmail.com>
 */
class userActions extends sfActions
{
  public function  postExecute() {
        $this->getResponse()->addHttpMeta('cache-control','private');
        $this->getResponse()->addHttpMeta('Pragma','no-cache');
        $this->getResponse()->addHttpMeta('Expires','-1');
    }
  public function executeNew(sfWebRequest $request)
  {
    $this->form = new userForm();
  }
  
  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new userForm();    

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($user = UserPeer::retrieveByPk($request->getParameter('id')), sprintf('Object user does not exist (%s).', $request->getParameter('id')));
    $this->form = new userForm($user);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($user = UserPeer::retrieveByPk($request->getParameter('id')), sprintf('Object user does not exist (%s).', $request->getParameter('id')));
    $this->form = new userForm($user);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    
    if ($form->isValid())
    {
      $user = $form->save();
      if($request->getParameter('sf_method')!='put')
      {
          $emailId = $user->getEmailId();
          $this->getUser()->setFlash('email', $emailId);
          // Send activation link to email
            $from = sfConfig::get('app_admin_email');
            $headers  = "From: Submitearticles<$from>\r\n";
            $headers .= "Reply-To: $from\r\n";
            $headers .= 'MIME-Version: 1.0' . "\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

            $activationConfig = sfConfig::get('app_user_activation');
            mail(
                  $emailId, // To
                  $activationConfig['subject'], // Subject
                  sprintf($activationConfig['message'], $user->getFirstName(), $this->generateUrl('activation_link', array('token' => $user->getToken(), 'email' => $emailId), true)),
                  $headers
                  );
          $this->redirect('@user_thankyou');

      }
      else
      {
          $this->redirect('@user_home');
      }
      
     }
  }

  public function executeShow(sfWebRequest $request)
  {
      $this->user = $this->getRoute()->getObject();
      $this->forward404Unless($this->user);


      $this->getResponse()->setTitle(html_entity_decode($this->user->getMetaTitle()), false);
      $this->getResponse()->addMeta('description', html_entity_decode($this->user->getMetaDescription()));
      $this->getResponse()->addMeta('keywords', html_entity_decode($this->user->getMetaKeyword()));

  }

  public function executeSign(sfWebRequest $request)
  {
      $this->form = new UserSignInForm();      
  }

  public function executeCheck(sfWebRequest $request)
  {
      $this->forward404Unless($request->isMethod('post'));
      $this->form = new UserSignInForm();

      $this->processSignInForm($request, $this->form);
      $this->setTemplate('sign');
  }

  protected function processSignInForm($request, $form)
  {
      $form->bind($request->getParameter($form->getName()));
      
      if($form->isValid())
      {
          $user = UserPeer::checkUserNamePassword($form->getValues());
          
          // Check for valid User & Password
          if($user)
          {
            // Sign in & save the article form(if exist)
              $this->getUser()->setAuthenticated(true);
              $this->getUser()->addCredential('author');

              // Save article form if exist
              if($this->getUser()->hasAttribute('form'))
              {
                  $form = $this->getUser()->getAttribute('form');
                  $form->setValue('user_id', $user->getId());
                  $form->save();
                  
                  $this->getUser()->getAttributeHolder()->remove('form');
                  
              }
              
              $this->getUser()->setAttribute('user_id', $user->getId());
              /*
               * Check if security questions already set
               */               
               if(PasswordAnswerPeer::countAnswersForUser($user->getId())!=2)
               {
               
              // Redirect to choose questions & answers
                 $this->redirect('password_answer/new');
              // $this->redirect('@user_home');
               }
               else
               {
                   $this->redirect('@user_home');
               }
          }

              $status = UserPeer::getUserStatus($form->getValues());
              switch($status)
              {
                  case '0':
                    $this->getUser()->setFlash('error', 'User Id/Password mismatch!');
                    break;
                  case '2':
                    $this->getUser()->setFlash('error', 'Account not activated!');
                    break;                    
              }
      }   
  }

  public function executeHome(sfWebRequest $request)
  {
      
  }

  public function executeLogout(sfWebRequest $request)
  {
      $this->getUser()->setAuthenticated(false);
      $this->getUser()->clearCredentials();
      $this->getUser()->getAttributeHolder()->remove('user_id');
      $this->redirect('user/sign');
  }

  public function executeThankYou(sfWebRequest $request)
  {
    
  }

  public function executeActivate(sfWebRequest $request)
  {
      $token = $request->getParameter('token');
      
      $this->forward404Unless($token);

      $activate = UserPeer::activateAuthorAccount(array('token' => $token));
      if(!$activate)
      {
         return sfView::ERROR;
      }
   }

   public function executeChangePassword(sfWebRequest $request)
   {
       $this->form = new ChangePasswordForm();
       if($request->isMethod(sfWebRequest::POST))
       {           
           $this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));

           if($this->form->isValid())
           {
               $this->form->save($this->getUser()->getAttribute('user_id'));
               $this->getUser()->setFlash('notice', 'Password has been changed successfully!');
               $this->redirect("@user_home");
           }
       }

       
   }

   public function executeForgotPassword(sfWebRequest $request)
   {
       /*
        * If a user forgot its password to login, ask user name
        */
       $this->form = new AskUserNameForm();
   }

   public function executeForgotPasswordStep2(sfWebRequest $request)
   {
       /*
        * Retrieve both questions & ask answers of them.
        */
       $this->form = new AskUserNameForm();
       $this->processFormForPassword($request, $this->form);
       $this->setTemplate('forgotPassword');
   }

   protected function processFormForPassword($request, $form)
   {
       $form->bind($request->getParameter($form->getName()));
       if($form->isValid())
       {
       /* If Email Id is valid then provide questions to get answers */
           if(UserPeer::countIfExist($form->getValue('user_name'))==1)
           {
           $this->getUser()->setAttribute('user_name', $form->getValue('user_name'));
           $this->redirect('@get_question');
           }
           else
           {
               $this->getUser()->setFlash('error', 'Username doesn\'t exist!');
           }
       }
   }

   public function executeGetQuestion(sfWebRequest $request)
   {
       $this->forward404Unless($this->getUser()->hasAttribute('user_name'));
       /* Find questions */
       $user = UserPeer::getUserForUserName($this->getUser()->getAttribute('user_name'));
       $passwordQuestionAnswers = $user->getPasswordAnswersJoinPasswordQuestion();
       if(count($passwordQuestionAnswers)==2)
       {
        $this->form1 = new PasswordAnswerForm($passwordQuestionAnswers[0]->setAnswer(''), array('name' => 'first', 'isForgot' => true));
   
        $this->form2 = new PasswordAnswerForm($passwordQuestionAnswers[1]->setAnswer(''), array('name' => 'second', 'isForgot' => true));
   
       }
       else
       {
           $this->sendPasswordToEmail($user);
            // $this->getUser()->setFlash('error', 'You haven\'t set your security questions!');
            // $this->redirect('forgot_password');
       }
   }

   public function executeCheckAnswers(sfWebRequest $request)
   {
       $this->forward404Unless($this->getUser()->hasAttribute('user_name') && $request->isMethod('post'));
       $user = UserPeer::getUserForUserName($this->getUser()->getAttribute('user_name'));
       $passwordQuestionAnswers = $user->getPasswordAnswersJoinPasswordQuestion();
       $this->checkIfAnswersValid($request, $passwordQuestionAnswers, $user);

       $this->redirect('@get_question');
   }
   protected function checkifAnswersValid($request, $answers, $user)
   {
       $first  = $request->getParameter('first');
       $second = $request->getParameter('second');
       $i =0;
       if($answers[0]->getAnswer() == $first['answer']){
           $i++;
       }

        if($answers[1]->getAnswer() == $second['answer']){
           $i++;
       }
       if($i == 2)$this->sendPasswordToEmail ($user);
       else{
           $this->getuser()->setFlash('error', 'Wrong Answers! Try again.');
       }
           
   }

   protected function sendPasswordToEmail($user)
   {
            $emailId = $user->getEmailId();
            $this->getUser()->setFlash('email', $emailId);

            // Send Password to email
            $from     = sfConfig::get('app_admin_email');

            $headers  = "From: Submitearticles<$from>\r\n";
            $headers .= "Reply-To: $from\r\n";
            $headers .= 'MIME-Version: 1.0' . "\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

            $activationConfig = sfConfig::get('app_user_forgot_password');
            mail(
                  $emailId, // To
                  $activationConfig['subject'], // Subject
                  sprintf($activationConfig['message'], $user->getFirstName(), $user->getUrlSlug(), $user->getPassword()),
                  $headers
                  );
            $this->redirect('@forgot_password_thanks');
   }

   public function executeForgotPasswordThanks(sfWebRequest $request)
   {
       
   }

}